﻿using System;

namespace EasyIot.WinApp
{
    class CProtocolHandle
    {
        public const char SPLIT1 = '&';
        public const char SPLIT2 = '#';
        const int HEAD1 = 0x49;// I
        const int HEAD2 = 0x4F;// O
        const int HEAD3 = 0x54;// T
        const int HEAD4 = 0x3D;// =

        public void Process(ByteBuffer bBuffer, CProtocolAnalysis analysis)
        {
            analysis.BagStatus = CProtocolAnalysis.EBagStatus.BagNone;
            analysis.WhetherToSend = false;

            int iPosition = bBuffer.GetPosition(); if (!bBuffer.HasRemaining()) return; 
            
            bool headok = false;

            while (bBuffer.HasRemaining())
            {
                byte head1 = bBuffer.GetByte();

                if (HEAD1 == head1)
                {
                    iPosition = bBuffer.GetPosition() - 1;
                    byte head2 = bBuffer.GetByte(); if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;
                    byte head3 = bBuffer.GetByte(); if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;
                    byte head4 = bBuffer.GetByte();
                    if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;
                    if (HEAD2 == head2 && HEAD3 == head3 && HEAD4 == head4)
                    {
                        headok = true;
                        break;
                    }
                    else
                    {
                        LogHelper.AppendLog("Error,Unable to parse the data(2):Position=" + iPosition + ",Index=" + bBuffer.GetPosition()  + ",Head2=" + head2);
                    }
                }
                else
                {
                    LogHelper.AppendLog("Error,Unable to parse the data(1):Position=" + iPosition + ",Index=" +  bBuffer.GetPosition()  + ",Head1=" + head1);
                }
            }

            if (!bBuffer.HasRemaining())
            {
                if (headok)
                {
                    if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;
                }
                return;
            }

            byte[] arrlen = bBuffer.GetByteArray(4); if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;
            int len = DataHelper.String2Int(DataHelper.ByteToString(arrlen)); if (-1 == len) return;
            byte[] source = bBuffer.GetByteArray(len); if (!analysis.IsRemainData(iPosition, bBuffer, analysis)) return;

            if (!bBuffer.HasRemaining())
            {
                bBuffer.Clear();
            }
            else
            {
                analysis.BagStatus = CProtocolAnalysis.EBagStatus.BagStick;
            }

            string data = DataHelper.ByteToString(source);
            if (null == data || 0 == data.Length || data.Length - 1 != data.LastIndexOf(SPLIT1))
            {
                return;
            }
            data = data.Substring(1, data.Length - 2);
            string[] item = data.Split(SPLIT1);
            if (null == item || 4 != item.Length)
            {
                return;
            }
            string uid = item[0];
            string taskid = item[1];
            int cmd = DataHelper.String2Int(item[2]);
            string content = item[3];

            analysis.Cmd = cmd;
            analysis.Uid = uid;
            analysis.TaskId = taskid;

            try
            {
                switch (cmd)
                {
                    case 1:
                        DataMgr.MainHandle.OnMessage("TCP信息：心跳反馈");
                        break;
                    case 3:
                        {
                            // 数据透传 
                            DataMgr.MainHandle.OnMessage("TCP信息：收到透传指令, cmd=" + cmd + " data=" + data);
                            analysis.WhetherToSend = true;
                            analysis.Msg = "ok";
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.AppendLog("error@" + ex.Message);
            }
        }  
    }
}